<template>
	<div class="college_data">
		<head-back-title title="教程内容"></head-back-title>
		<el-card>
			<el-form ref="form" :model="form" label-width="80px" :rules="FormRules">
				<el-row>
					<el-col :span="16">
						<el-form-item label="标题" prop="name">
							<el-input v-model="form.name" placeholder="请输入标题" prefix-icon="el-icon-edit"></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="5">
						<el-form-item label="教程分类" prop="class_id">
							<el-select v-model="form.class_id" placeholder="请选择教程分类">
								<el-option v-for="item in classifyList" :key="item.class_id" :label="item.class_name" :value="item.class_id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="排序" prop="sort">
							<el-input v-model="form.sort" placeholder="请输入排序"></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="8">
						<el-form-item label="封面图:" class="upload-box" prop="image">
							<div class="mainImg">
								<div class="goods-img-upload">
									<div class="goods-img-upload-btns">
										<el-upload ref="upload" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return upload(res); } "
										 accept="image/*">
											<el-button type="primary" size="small">上传图片</el-button>
										</el-upload>
										<el-button type="danger" size="small" @click="restImg('img')">重置</el-button>
										<div class="el-upload__tip">小于20MB</div>
									</div>
									<div class="goods-img-upload-imgs">
										<el-image v-show="!form.image">
											<div slot="error"></div>
										</el-image>
										<img v-if="form.image" :src="form.image" class="avatar" />
									</div>
								</div>
							</div>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="上传视频:" class="upload-box" prop="video">
							<div class="goods-img-upload">
								<div class="goods-img-upload-btns">
									<el-upload ref="upload" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return uploadVideo(res); } "
									 accept="video/mp4,avi">
										<el-button type="primary" size="small">上传视频</el-button>
									</el-upload>
									<el-button type="danger" size="small" @click="restImg('video')">重置</el-button>
									<div class="el-upload__tip">小于100MB</div>
								</div>
								<div class="goods-img-upload-imgs">
									<el-image v-show="!form.video">
										<div slot="error"></div>
									</el-image>
									<div class="vice_big_box" style="width: 500px; margin-left: 25px;" v-show="form.video">
										<video controls="controls" :src="form.video" style="width: 300px;"></video>
									</div>
								</div>
							</div>
						</el-form-item>
					</el-col>
				</el-row>

				<div class="rich-text">
					<el-form-item label="" prop="content">
						<quill-editor class="ql-editor" ref="myQuillEditor" v-model="form.content" :options="editorOption"></quill-editor>
					</el-form-item>
				</div>

				<el-button type="primary" @click="onSubmit('form')">发布</el-button>
				<el-button @click="goBack">取消</el-button>
			</el-form>
		</el-card>
	</div>
</template>

<script>
	import md5 from 'md5'
	import 'quill/dist/quill.core.css'; // import styles
	import 'quill/dist/quill.snow.css'; // for snow theme
	import 'quill/dist/quill.bubble.css'; // for bubble theme
	import {
		quillEditor,
		Quill
	} from 'vue-quill-editor';
	import {
		container,
		addQuillTitle
	} from 'quill-video-image-module';
	import {
		ImageExtend,
		QuillWatch
	} from 'quill-video-image-module';
	import {
		VideoExtend,
		QuillVideoWatch
	} from 'quill-video-image-module';

	// 引入video模块并注册
	import video from 'quill-video-image-module/video';
	Quill.register(video, true);

	Quill.register('modules/ImageExtend', ImageExtend);
	Quill.register('modules/VideoExtend', VideoExtend);

	import ImageResize from 'quill-image-resize-module';
	Quill.register('modules/imageResize', ImageResize);

	export default {
		components: {
			quillEditor
		},
		data() {
			return {
				classifyList: [{
						class_name: '商城教程',
						class_id: 1
					},
					{
						class_name: '商家端教程',
						class_id: 2
					}
				],
				form: {
					name: '',
					class_id: '',
					video: '',
					sort: 0,
					content: '',
					image: '',
				},
				FormRules: {
					name: [{
						required: true,
						message: '请输入标题'
					}],
					class_id: [{
						required: true,
						message: '请选择教程分类'
					}],
					sort: [{
						required: true,
						message: '请输入排序'
					}],
					image: [{
						required: true,
						message: '请上传图片'
					}],
					video: [{
						required: true,
						message: '请上传视频'
					}],
					content: [{
						required: true,
						message: '请编写文章内容'
					}]
				},
				// 富文本框参数设置
				editorOption: {
					modules: {
						imageResize: {},
						ImageExtend: {
							loading: true, // 可选参数 是否显示上传进度和提示语
							name: 'file[]', // 图片参数名
							size: 1, // 可选参数 图片大小，单位为M，1M = 1024kb
							action: `${this.$domain}api/Upimg/UpImg`, // 服务器地址, 如果action为空，则采用base64插入图片
							// response 为一个函数用来获取服务器返回的具体图片地址
							// 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
							// 则 return res.data.url
							response: res => {
								return res.datas[0];
							},
							headers: () => {}, // 可选参数 设置请求头部
							start: () => {}, // 可选参数 自定义开始上传触发事件
							end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
							error: () => {}, // 可选参数 自定义网络错误触发的事件
							change: (xhr, formData) => {
								formData.append('timestamp', Math.round(new Date() * 1000));
								formData.append('port', 'pc');
								formData.append('sign', this.getSign());
								formData.append('key', localStorage.getItem('token'));
							}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
							sizeError: () => {
								this.$message({
									message: '图片不能大于1M',
									type: 'warning'
								});
							}
						},
						VideoExtend: {
							loading: true,
							name: 'file[]',
							size: 100, // 可选参数 视频大小，单位为M，1M = 1024kb
							action: `${this.$domain}api/Upimg/UpVideo`, // 视频上传接口
							headers: xhr => {
								// set custom token(optional)
							},
							response: res => {
								// video uploaded path
								// custom your own
								return res.datas;
							},
							change: (xhr, formData) => {
								formData.append('timestamp', Math.round(new Date() * 1000));
								formData.append('port', 'pc');
								formData.append('sign', this.getSign());
								formData.append('key', localStorage.getItem('token'));
							}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
							sizeError: () => {
								this.$message({
									message: '视频不能大于100M',
									type: 'warning'
								});
							}
						},
						toolbar: {
							container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
							handlers: {
								image: function() {
									// 劫持原来的图片点击按钮事件
									QuillWatch.emit(this.quill.id);
								},
								video: function() {
									QuillVideoWatch.emit(this.quill.id);
								}
							}
						}
					}
				}
			};
		},
		methods: {
			// 返回
			goBack() {
				this.$router.go(-1);
			},
			// 提交资讯
			onSubmit(formName) {
				this.$refs[formName].validate(valid => {
					if (valid) {
						if (this.$route.query.isAdd == 0) {
							this.$http(this.$ApiList.CollegeUp, this.form).then(res => {
								this.$layer.msg('修改成功');
								this.$router.push('/college_lists');
							});
						} else {
							this.$http(this.$ApiList.CollegeAdd, this.form).then(res => {
								this.$layer.msg('提交成功');
								this.$router.push('/college_lists');
							});
						}
					} else {
						this.$layer.msg('请填写完整信息后提交');
					}
				});
			},
			// 重置图片
			restImg(type) {
				switch (type) {
					case 'img':
						this.form.image = '';
						break;
					case 'video':
						this.form.video = '';
						break;
				}
			},
			// 图片上传
			upload(params) {
				//console.log(params);
				const file = params.file,
					fileType = file.type,
					isJPGPNG = file.type === 'image/jpeg' || 'image/png',
					isLt1MB = file.size / 1024 <= 1024;
				if (!isJPGPNG) {
					this.$message.error('只能上传图片格式png、jpg!');
					return;
				}
				if (!isLt1MB) {
					this.$message.error('图片不能大于1M');
					return;
				}

				let image = new FormData();
				image.append('file[]', file);

				this.$http(this.$ApiList.publicUpload, image).then(res => {
					this.form.image = res.datas[0];
				});
			},
			// 视频上传
			uploadVideo(params) {
				const file = params.file,
					isLt100MB = file.size / 1024 / 1024 < 100;
				if (!isLt100MB) {
					this.$message.error('视频不能大于100MB！');
					return;
				}
				const form = new FormData();
				form.append('file[]', file);
				this.$http(this.$ApiList.UpVideo, form).then(res => {
					this.form.video = res.datas;
				});
			},
			getNewsDetails(id) {
				let data = {
					college_id: id,
				};
				this.$http(this.$ApiList.CollegeLists, data).then(res => {
					console.log(res.datas[0]);
					this.form.name = res.datas[0].name
					this.form.class_id = res.datas[0].class_id
					this.form.video = res.datas[0].video
					this.form.sort = res.datas[0].sort
					this.form.content = res.datas[0].content
					this.form.image = res.datas[0].image
					this.form.college_id = res.datas[0].college_id
				});
			},
			getSign() {
				let data = {
					key: localStorage.getItem('token'),
					timestamp: Math.round(new Date() * 1000),
					port: 'pc'
				}
				// 获取签名开始
				let obj = 'jjds2020+'
				let newObj = this.objKeySort(data)
				for (let i in newObj) {
					obj += i + '=' + newObj[i] + '&'
				}
				obj = obj.substring(0, obj.length - 1)
				obj += '+jjds2020'
				obj = md5(obj)
				return obj
			},
			// 参数排序
			objKeySort(obj) {
				var newkey = Object.keys(obj).sort();
				var newObj = {};
				for (var i = 0; i < newkey.length; i++) {
					newObj[newkey[i]] = obj[newkey[i]];
				}
				return newObj;
			}
		},
		created() {
			if (this.$route.query.isAdd == 0) {
				this.getNewsDetails(this.$route.query.id);
			}
		},
		mounted() {
			addQuillTitle();
		}
	};
</script>
<style lang="scss">
	.college_data {
		padding: 0 40px;


		.avatar-uploader .el-upload {
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
		}

		.avatar-uploader .el-upload:hover {
			border-color: #409eff;
		}

		.avatar-uploader-icon {
			font-size: 28px;
			color: #8c939d;
			width: 178px;
			height: 178px;
			line-height: 178px;
			text-align: center;
		}

		.avatar {
			margin-left: 25px;
			width: 178px;
			height: 178px;
			display: block;
		}

		.rich-text {
			margin-bottom: 20px;
		}

		.rich-text .el-form-item__content {
			margin-left: 0 !important;
		}

		.ql-editor {
			min-height: 500px;
		}

		/* 解决粘贴后光标会自动弹到文档的初始位置 */
		.ql-clipboard {
			position: fixed;
			display: none;
			left: 50%;
			top: 50%;
		}

		.upload-box {
			padding-left: 40px;

			.goods-img-upload {
				display: flex;

				.goods-img-upload-imgs {
					flex: 1;
					align-items: flex-start;

					.el-image {
						width: 178px;
						height: 178px;
						border: solid 1px #e5e5e5;
						margin-left: 25px;
						vertical-align: top;
					}
				}

				.goods-img-upload-imgs-info {
					width: 100%;
					max-width: 660px;
					border: solid 1px #e5e5e5;
					margin-left: 25px;
					min-height: 390px;

					.goods-img-upload-imgs-info-box {
						position: relative;

						.el-icon-error {
							position: absolute;
							font-size: 20px;
							color: #ef3030;
							right: 5px;
							top: 5px;
							z-index: 1;
							background-color: #fff;
							border-radius: 50%;
							cursor: pointer;
						}
					}

					.el-image {
						width: 100%;
						vertical-align: top;
					}
				}

				.vice_big_box {
					position: relative;
					display: inline-block;
					vertical-align: top;
					margin-bottom: 20px;

					.el-icon-error {
						position: absolute;
						font-size: 20px;
						color: #ef3030;
						right: 5px;
						top: 5px;
						z-index: 1;
						background-color: #fff;
						border-radius: 50%;
						cursor: pointer;
					}
				}
			}

			.el-upload__tip {
				width: 80px;
				text-align: center;
			}

			.el-form-item__label {
				float: none;
			}

			.el-form-item__content {
				margin-left: 0 !important;

				.el-button--danger {
					width: 80px;
					background-color: #37c1d6;
					border-color: #37c1d6;
				}
			}
		}
	}
</style>
